<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Spatie\Permission\Traits\HasPermissions;
use Spatie\Permission\Traits\HasRoles;

class Permissions extends BaseModel
{
    protected $connection = 'mysql';
    use HasRoles;
    protected $table = 'permissions';
    protected $fillable = ['name','desc'];
    protected $attributes = [
        'guard_name' => 'web'
    ];
    private $fields = ['id','name','desc','pid','created_at'];
    CONST PARENT_ID = 0;
    
    public function getList(Request $request){
        // $limit = $request->input('limit',100);
        $limit = 100;
        $page = $request->input('page',1);
        
        $query = new Permissions();
        
        // todo 搜索
        
        $permission = $query->where(['pid' => self::PARENT_ID])->paginate($limit,$this->fields,'page',$page);
        return collect($permission)->map(function ($item,$key){
            if($key === 'data'){
                return collect($item)->map(function ($it){
                    $it['hasChildren'] = true;
//                    $it['children'] = Permissions::where(['pid' => $it['id']])->get($this->fields);
                    return $it;
                });
            }
            return $item;
        });
    }
    
    public function getPermissionById($id) {
        return self::where('pid', $id)->get()->toArray();
    }
}
